#!/usr/bin/env python
#-*- coding:utf-8 -*-

"""
    PySeq0 - a python sequencer
    (c) by Tobias Sauer 2011
    Copyright: GPL v2 only
    http://leichtdio.de
    tobias@leichtdio.de
    
    Google Code:
    http://pyseq0.leichtdio.de

    @ToDo:
        - Wenn mehrere Loops in einem Beat: Wie Drum behandeln > DrumClass anpassen
        - Mehrere Noten gleichzeitig spielbar
        - Mehrere Noten versetzt spielbar
        > evtl von WriteShort auf Write umbauen und komplette MidiSeq übergeben
"""

import thread

import pattern

class DrumClass:
    """
        Verwaltet DrumLoops
    """
    def __init__ (self, groupdic, bpm, midipointer, length = 1):
        self.meta = {"name" : groupdic["name"]}
        self.length = length
        self.portdic = {}
        self.isplaying = False
        self.midi = midipointer
        self.tik = ((60000. / float(bpm)) * 4) * 1./16.
        content = {}
        for drum in groupdic["content"]:
            content[drum] = self.converter(groupdic["content"][drum])
            self.portdic[drum] = self.midi.get_midiport(drum)
        self.pads = []
        for drum in content:
            self.pads.append(pattern.Patt(content[drum], self.midi, drum))

    def converter (self, drumpad):
        midilist = []
        for row in drumpad:
            if row == "X":
                midilist.append((69, 127, 0, 1./16.))
            else:
                midilist.append(("sleep", 1./16.))
        return midilist


    def internplay(self, pad):
        self.isplaying = True
        for note in pad.getnotes():
            self.midi.playnote(self.portdic[pad.name], note.return_noteon(), self.tik)

    def stop (self):
        self.isplaying = False

    def play (self):
        for pad in self.pads:
            thread.start_new_thread(self.internplay, (pad, ))

class LoopClass:
    """
        Verwaltet einen einzigen Loop
    """
    def __init__(self, loopdic, bpm, midipointer):
        self.meta = {
                     "name" : loopdic["name"],
                     "midiname" : loopdic["midiname"],
                     "midiport" : loopdic["midiport"],
                     "autoconnect" : loopdic["autoconnect"],
                    }
        self.length = loopdic["length"]
        self.isplaying = False
        self.midi = midipointer
        if self.meta["autoconnect"]:
            self.get_midiport()
        self.pad = pattern.Patt(loopdic["content"], midipointer)
        self.bpmms = (60000. / float(bpm)) * 4

    def get_midiport(self):
        self.port = self.midi.get_midiport(self.meta["midiname"])

    def stop_loop(self):
        self.isplaying = False

    def play(self):
        self.isplaying = True
        for note in self.pad.getnotes():
            self.midi.playnote(self.port, note.return_noteon(), self.bpmms * note.duration)
